package com.come4loves.core.comunicate.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import com.come4loves.core.comunicate.ComunicateConst;
import com.come4loves.core.comunicate.protocol.Response;

public class ServerEncoder extends MessageToByteEncoder<Response> {

	/**
	 * 头长度 module+cmd+statuscode
	 */
	private static final int SERVER_HEADER_LENGTH = 8;
	@Override
	protected void encode(ChannelHandlerContext ctx, Response msg,
			ByteBuf out) throws Exception {
		if (msg.getValue() == null) {
			out.writeInt(ComunicateConst.HEADER_FLAG);
			out.writeInt(SERVER_HEADER_LENGTH);
			out.writeByte(msg.getModule());
			out.writeByte(msg.getCmd());
			out.writeInt(msg.getArgs());
			out.writeShort(msg.getStatusCode());
		} else {
			byte[] value = msg.getValue();
			int valueLen = value.length;
			out.writeInt(ComunicateConst.HEADER_FLAG);
			out.writeInt(SERVER_HEADER_LENGTH + valueLen);
			out.writeByte(msg.getModule());
			out.writeByte(msg.getCmd());
			out.writeInt(msg.getArgs());
			out.writeShort(msg.getStatusCode());
			out.writeBytes(value);
		}
		
	}

}
